package com.app.project;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.Stack;
import java.util.TimerTask;
import java.util.UUID;

import com.app.DB.Customers;
import com.app.DB.SegwayDetails;
import com.app.general.DateTime;
import com.app.project.BESM_LoginActivity.InsertService;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;

public class BESM_MainForUser   extends Activity 
								implements  GooglePlayServicesClient.ConnectionCallbacks,
								GooglePlayServicesClient.OnConnectionFailedListener,
								LocationListener,
								OnMapClickListener, 
								OnMapLongClickListener, 
								OnMarkerClickListener {
	
	
	// -------------Bluetooth----------------------//
	private String address;
	private BluetoothDevice device;
	private static final String Name = "Bluetoot";
	private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private static final int MASSAGE_READ = 100;
	private ConnectThread mConnectThread = null;
	private AcceptThread mAcceptThread = null;
	private ConnectedThread mConnectedThread = null;
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothSocket socket = null;
	private String mDeviceName = "Admin";
	private StringBuilder sb = new StringBuilder();
	private String Android_Command ="";
	private static final String Balance = "B";
	private static final String Battery = "S";
	private Handler Handler = new Handler();
	
	// -------------G_Map----------------------//
	private LocationClient mLocationclient;
	private Location mCurrentLocation;
	private GoogleMap map;
    private double lat;
    private double lng;
    private LatLng currentLanLng;
    private String msg;
    private LocationRequest request;
    private MarkerOptions MarkerMe;
    Double[] AREADRAW;
    boolean markerClicked = false;
    
    // -------------Monitor----------------------//
    EditText CarID,CarUserName,CarSpeed,CarLocation,CarBattery,CarBalance,CarTimeCount;
    Button buttonB,buttonS,buttonClear;
    ImageView ImageUser;
    
    // -------------DataBase----------------------//
    private ResultSet rs = null;
    private String ServiceOID ;
    private String IsMessage = "0" ;
    private String UserName ;
    
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    public static final int DIALOG_CheckInternet_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	private static final int END = 0;
	private static final int UPDATE = 1;
	private int OPERATION ;
	private String TimeUserCount = "Unlimited";
	private String MessageFromServer = "";
	
	Stack<String> st = new Stack<String>();
	private ListView mDataView;
	private ArrayAdapter<String> mArrayAdapter;
	private Bitmap camera_take;
	BESM_CheckOnline Net = new BESM_CheckOnline();
	DateTime mDatetime = new DateTime();
	
	//-----------------------Boolean------------------------//
	private Boolean aCheckSelectFromServer = false;
	private Boolean aCheckInsertToServer = false;
	private Boolean aONLINE = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_map);
		
		CarID = (EditText) findViewById(R.id.A_Main_carid);
		CarUserName = (EditText) findViewById(R.id.A_Main_username);
//		CarSpeed = (EditText) findViewById(R.id.A_Main_carspeed);
//		CarLocation = (EditText) findViewById(R.id.A_Main_location);
	    CarBattery = (EditText) findViewById(R.id.A_Main_battery);
	    CarBalance = (EditText) findViewById(R.id.A_Main_Balance);
	    CarTimeCount = (EditText) findViewById(R.id.A_Main_timecount);
	    
	    ImageUser = (ImageView)findViewById(R.id.A_Main_imageuser);
	    ImageUser.setOnClickListener(LatsLocation);
	    
	    buttonB = (Button)findViewById(R.id.A_Main_buttonB);
	    buttonB.setOnClickListener(LatsLocation);
	    buttonS = (Button)findViewById(R.id.A_Main_buttonS);
	    buttonClear = (Button)findViewById(R.id.A_Main_buttonClear);
	    ImageUser = (ImageView)findViewById(R.id.A_Main_imageuser);
	    ImageUser.setOnClickListener(LatsLocation);
	    
		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			mDeviceName = (String) bundle.get("Device Name");
			ServiceOID = (String) bundle.get("OID");
			address = (String) bundle.get("Device Address");
			camera_take = (Bitmap) bundle.get("Pic");
			if(camera_take!=null){
				((ImageView) ImageUser).setImageBitmap(camera_take);
			}
			UserName = (String) bundle.get("UserName");
			TimeUserCount = (String) bundle.get("TimeUserCount");
        	
		}
		
		this.setTitle("Connect Car "+ mDeviceName);
		CarID.setText(mDeviceName);
		CarUserName.setText(UserName);
    	CarTimeCount.setText(TimeUserCount);
    	CarSpeed.setText("HighSpeed ^^");
		
		mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
		device = mBluetoothAdapter.getRemoteDevice(address);
		
		if(mAcceptThread == null){
			mAcceptThread = new AcceptThread();
			mAcceptThread.start();
		}
		if(mConnectThread == null){
			mConnectThread = new ConnectThread(device);
			mConnectThread.start();
		}
		
		mArrayAdapter = new ArrayAdapter<String>(this, R.layout.databluetooth);
		mDataView = (ListView) findViewById(R.id.A_Main_listmessage);
		mDataView.setAdapter(mArrayAdapter);
		
		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.Map_Map)).getMap();
	    map.setIndoorEnabled(true);
	    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
	    map.setOnMapClickListener(this);
	    map.setOnMapLongClickListener(this);
	    map.setOnMarkerClickListener(this);
	    
		mLocationclient = new LocationClient(this,this,this);
		
		request = LocationRequest.create();
		request.setInterval(1000);
		request.setFastestInterval(1000);
		request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		
		MarkerMe = new MarkerOptions();
		MarkerMe.title("Admin");
		MarkerMe.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
		
		//----------Start_Tread---------------------//
		Handler.removeCallbacks(aUpdateCarBalance);
	    Handler.postDelayed(aUpdateCarBalance,5000);
	    Handler.removeCallbacks(aUpdateCarBattery);
	    Handler.postDelayed(aUpdateCarBattery, 5000);
	    Handler.removeCallbacks(aUpdate);
	    Handler.postDelayed(aUpdate, 5000);
	    
	    Handler.removeCallbacks(aUpdateService);
		Handler.postDelayed(aUpdateService, 10000);
		Handler.removeCallbacks(aUpdateTimeCount);
		Handler.postDelayed(aUpdateTimeCount, 10000);
		Handler.removeCallbacks(aCheckMessage);
		Handler.postDelayed(aCheckMessage, 10000);
	}
	
	public void onStart(){
		super.onStart();
		mLocationclient.connect();
//		Toast.makeText(BESM_MainForUser.this, "In the onStart() event",
//             Toast.LENGTH_SHORT).show();
	}
	
	
	public void onStop(){
		mLocationclient.disconnect();
		super.onStop();
		Toast.makeText(BESM_MainForUser.this, "In the onStop() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onPause(){
		super.onPause();
		Toast.makeText(BESM_MainForUser.this, "In the onPause() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onRestart(){
		Handler.removeCallbacks(aUpdateCarBalance);
	    Handler.removeCallbacks(aUpdateCarBattery);
	    Handler.removeCallbacks(aUpdate);
	    Handler.removeCallbacks(aUpdateService);
		Handler.removeCallbacks(aUpdateTimeCount);
		Handler.removeCallbacks(aCheckMessage);
		super.onRestart();
		Toast.makeText(BESM_MainForUser.this, "In the onRestart() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onDestroy(){
		Handler.removeCallbacks(aUpdateCarBalance);
	    Handler.removeCallbacks(aUpdateCarBattery);
	    Handler.removeCallbacks(aUpdate);
	    Handler.removeCallbacks(aUpdateService);
		Handler.removeCallbacks(aUpdateTimeCount);
		Handler.removeCallbacks(aCheckMessage);
		super.onDestroy();
		Toast.makeText(BESM_MainForUser.this, "In the onDestroy() event",
                 Toast.LENGTH_SHORT).show();
	}
	
	public void onResume() {
		super.onResume();
	    
	}
	
	// -------------Event_Button----------------------//
	
	private Runnable aUpdateCarBalance = new Runnable(){

		public void run() {
			Android_Command=Balance;
			int a=st.size();
			if(a>5){
				
			}else{
				st.push(Android_Command);
				
			}
			Handler.postDelayed(this, 500);
		} 	
    };
    
    private Runnable aUpdate = new Runnable(){

		public void run() {
			if(st.isEmpty()){
        		
        	}else{
            	Android_Command=st.pop().toString();
            	mConnectedThread.write(Android_Command);
        	}
			Handler.postDelayed(this, 100);
		} 	
    };
    
    private Runnable aUpdateCarBattery = new Runnable(){

		public void run() {
			Android_Command=Battery;
			int a=st.size();
			if(a>10){
				
			}else{
				st.push(Android_Command);
			}
			Handler.postDelayed(this, 10000);
		} 	
    };
  
	
	// -------------Event_Bluetooth----------------------//
	private class AcceptThread extends Thread{
		private final BluetoothServerSocket mmServerSocket;
		
		public AcceptThread(){
			BluetoothServerSocket tmp = null;
			try{
				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(Name, MY_UUID);
			}catch(IOException e){
				
			}
			mmServerSocket = tmp;
		}
		
		public void run(){
			while(true){
				try{
					socket = mmServerSocket.accept();
				}catch(IOException e){
					break;
				}
				if(socket != null){
					mConnectedThread = new ConnectedThread(socket);
					mConnectedThread.start();
					try{
						mmServerSocket.close();
					}catch(IOException e){
						e.printStackTrace();
					}
					break;
				}
			}
		}
		public void cancle(){
			try{
				mmServerSocket.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	private class ConnectThread extends Thread{
		private final BluetoothSocket mmSocket;
		@SuppressWarnings("unused")
		private final BluetoothDevice mmDevice;
		
		public ConnectThread(BluetoothDevice device){
			BluetoothSocket tmp = null;
			mmDevice = device;
			try{
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
			}catch(IOException e){
				
			}
			mmSocket = tmp;
		}
		
		public void run(){
			mBluetoothAdapter.cancelDiscovery();
			try{
				mmSocket.connect();
			}catch(IOException connectException){
				try{
					mmSocket.close();
				}catch(IOException closeException){
					
				}
				return;
				
			}
			mConnectedThread = new ConnectedThread(mmSocket);
			mConnectedThread.start();
		}
		
		public void cancle(){
			try{
				mmSocket.close();
			}catch(IOException e){
				
			}
		}
	}
	
	private class ConnectedThread extends Thread{
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;
		
		public ConnectedThread(BluetoothSocket socket){
			//Log.d("THREAD", "constructor");
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			try{
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			}catch(IOException e){
				
			}
			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}
		

		public void run(){
			Log.d("THREAD", "inside run" );
			byte[] buffer =new byte[256];
			int bytes;
			while (true) {
//				Log.d("in loop", "waiting for data");
				try{
					bytes = mmInStream.read(buffer);
					mHandler.obtainMessage(MASSAGE_READ, bytes, -1,buffer).sendToTarget();
//					
					//SystemClock.sleep(1000);
//					Log.d("recieve", "b " + bytes);
				}catch(IOException e){
					break;
				}
				
			}
		}
		
		public void write(String message){
			Log.d("TAG", "...Data to send: " + message + "...");
			byte[] msgBuffer = message.getBytes();
			try{
				mmOutStream.write(msgBuffer);
			}catch(IOException e){
				Log.d("TAG", "...Error data send: " + e.getMessage() + "...");  
			}
		}
		@SuppressWarnings("unused")
		public void cancle(){
			try{
				mmSocket.close();
			}catch(IOException e){
				
			}
		}
	}
	
	private final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MASSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				String strIncom = new String(readBuf, 0, msg.arg1);
//				mArrayAdapter.add("Arduino : "+strIncom.toString());
				sb.append(strIncom);												// append string
            	int endOfLineIndex = sb.indexOf("\r\n");							// determine the end-of-line
            	if (endOfLineIndex > 0) { 											// if end-of-line,
            		String sbprint = sb.substring(0, endOfLineIndex);				// extract string
                    sb.delete(0, sb.length());
                    if(Android_Command.equals(Battery)){
                    	CarBattery.setText(sbprint); 
                    }else if(Android_Command.equals(Balance)){
                    	CarBalance.setText(sbprint); 
                    }
                }
     
                break;
                
			}
			
		}
	};
	
	
	// -------------Event_Gmap----------------------//
	
	public void drawOnmap(){
		PolygonOptions area = new PolygonOptions();
		AREADRAW = new Double[] {
				18.804671,98.9745332,
				18.804851,98.9768982,
				18.802796,98.9769042,
				18.802978,98.9743967
				};
		
		int i=0;
		while(i<AREADRAW.length-1){
			area.add(new LatLng(Double.valueOf(AREADRAW[i]),Double.valueOf(AREADRAW[i+1])));
			i=i+2;
		}

		area.strokeWidth(3);
		area.strokeColor(Color.BLUE);
		area.fillColor(Color.argb(64, 0, 255, 0));
		map.addPolygon(area);
	}
	
	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onMapLongClick(LatLng arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		map.clear();
		drawOnmap();
		lat = location.getLatitude();
		lng = location.getLongitude();
		// สร้างออบเจ็ค LatLng เก็บค่าพิกัด
		currentLanLng = new LatLng(lat, lng);
		// ย้ายกล้อง เเละปักหมุด
		//map.animateCamera(CameraUpdateFactory.newLatLng(currentLanLng));
		map.addMarker(MarkerMe.position(currentLanLng));
		msg = String.valueOf(lat)+"\n"+String.valueOf(lng);

		CarLocation.setText(msg);
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onConnected(Bundle arg0) {
		// TODO Auto-generated method stub
		LatsLocation();	
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		
	} 
	
	public void LatsLocation(){
		// ตรวจสอบการเชื่อมต่อว่าเชื่อมต่อ Location Services แล้ว
		if(mLocationclient.isConnected()){
    		map.clear(); //ลบหมุดเดิม
    		drawOnmap();
    		// ขอตำแหน่งปัจจุบันจาก Location จาก Location Service
    		mCurrentLocation = mLocationclient.getLastLocation();
    		// หาพิกัด 
    		lat = mCurrentLocation.getLatitude();
    		lng = mCurrentLocation.getLongitude();
    		
    		// สร้างออบเจ็ค LatLng เก็บค่าพิกัด
    		currentLanLng = new LatLng(lat, lng);
    		// ย้ายกล้อง เเละปักหมุด
    		map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLanLng,18));
    		map.addMarker(MarkerMe.position(currentLanLng));
    		msg = "Current location: "+String.valueOf(lat)+","+String.valueOf(lng);
        	
    	}else{
    		msg = "Cannot Connect Location";
    	}
    	mLocationclient.requestLocationUpdates(request, BESM_MainForUser.this);
	}
	
	
	private Runnable aUpdateService = new Runnable(){

		public void run() {
			OPERATION=UPDATE;
        	new  UpdateService().execute();
			Handler.postDelayed(this, 60000);
		} 	
    };
    
    private Runnable aCheckMessage = new Runnable(){

		public void run() {
        	new  SelectServiceFromServer().execute();
			Handler.postDelayed(this, 30000);
		} 	
    };
    
    private Runnable aUpdateTimeCount = new Runnable(){

		public void run() {
			
			if(!CarTimeCount.getText().toString().equals("")){
				TimeUserCount=CarTimeCount.getText().toString();
				int Time = mDatetime.convertTimess(CarTimeCount.getText().toString());
				Time = Time-1;
				int HH = Time/3600;
				int mm = (Time%3600)/60;
				int ss = (Time%3600)%60;
				
				String HH1="-",mm1="-",ss1="-";
				
				if (mm <= (10) && HH == 0) {
					//aAlertUserTime();
				}
				
				if(HH<10){
					HH1="0"+String.valueOf(HH);
				}else{
					HH1=String.valueOf(HH);
				}
				if(mm<10){
					mm1="0"+String.valueOf(mm);
				}else{
					mm1=String.valueOf(mm);
				}
				if(ss<10){
					ss1="0"+String.valueOf(ss);
				}else{
					ss1=String.valueOf(ss);
				}
				CarTimeCount.setText(HH1+":"+mm1+":"+ss1);
			}
			Handler.postDelayed(this, 1000);
		} 	
    };

	
	private OnClickListener LatsLocation = new OnClickListener() {
	        public void onClick(View v) {
	        	LatsLocation();
	        }
	}; 
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Updating.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }
	//-----------InsertService-Loading----------------------------------//
    public class UpdateService extends AsyncTask<String, Void, Void> {
        @SuppressWarnings("deprecation")
		protected void onPreExecute() {
        	super.onPreExecute();
        	if(Net.networkSignOn()){
        		aONLINE = true;
        		showDialog(DIALOG_DOWNLOAD_PROGRESS);
        	}else{
        		aONLINE = false;
        		//ALERT
        	}
        }
        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
        	SegwayDetails usr;
        	if(aONLINE){
        		switch (OPERATION){
        		case END:
        			Handler.removeCallbacks(aUpdateTimeCount);
        			usr = new SegwayDetails(
        					ServiceOID,
                			null,
                			null,
            				"1",
            				null,	
            				null,
            				null,
            				null,
            				null,
            				null,
            				null,
            				"0",
            				null,
            				null
            		);
            		try {
        				if(usr.OperationData("End") != null){
        					aCheckInsertToServer = true;
        				}else{
        					Toast.makeText(BESM_MainForUser.this, "404",
       			                 Toast.LENGTH_SHORT).show();
        				}
        			} catch (Exception e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			break;
        		case UPDATE:
        			usr = new SegwayDetails(
        					ServiceOID,
                			null,
                			"1",
            				"0",
            				null,	
            				String.valueOf(TimeUserCount),
            				CarBalance.getText().toString(),
            				String.valueOf(lat),
            				String.valueOf(lng),
            				null,
            				"Batterry : "+CarBattery.getText().toString()+" ,Speed : "+CarSpeed.getText().toString(),
            				null,
            				null,
            				null
            		);
            		try {
        				if(usr.OperationData("UpdateFromUser") != null){
        					aCheckInsertToServer = true;
        				}else{
        					Toast.makeText(BESM_MainForUser.this, "404",
        			                 Toast.LENGTH_SHORT).show();
        				}
        			} catch (Exception e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			break;
        		default:
    	            return null;
        		}
        	}
        	
    		return null;
        }

        @SuppressWarnings("deprecation")
		protected void onPostExecute(Void unused) {
        	if(aCheckInsertToServer){
        		 dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                 removeDialog(DIALOG_DOWNLOAD_PROGRESS);
                 aCheckInsertToServer = false;
        	}else{
        		mArrayAdapter.add("Cannot connet!!\n");
        	}
            
        }
    }
	 
	//-----------SelectServiceFromServer----------------------------------//
	    public class SelectServiceFromServer extends AsyncTask<String, Void, Void> {
			protected void onPreExecute() {
	        	super.onPreExecute();
	        }
	        @Override
	        protected Void doInBackground(String... params) {
	            // TODO Auto-generated method stub
	        	rs=null;
	        	SegwayDetails usr = new SegwayDetails();
		    	try{
		    		rs = usr.selectSegwayDetails(ServiceOID, "");
		    		if(rs.next()){
		    			IsMessage = rs.getString("IsMessage");
		    			if(IsMessage.equals("1")){
		    				MessageFromServer = rs.getString("ServerMessage");
		    				aCheckSelectFromServer = true;
		    			}
		    		}
		    	}catch (Exception e){
		    		
		    	}
	    		
	    		return null;
	        }

			protected void onPostExecute(Void unused) {
	        	
	            if(aCheckSelectFromServer){
	            	if(MessageFromServer.equals("STOP")){
	            		mArrayAdapter.add("ServerComman : Stop this car.\n");
	            	}else if(MessageFromServer.equals("RESTART")){
	            		mArrayAdapter.add("ServerComman : ReStart this car.\n");
	            	}
	            	aCheckSelectFromServer = false;
	            }else{
	            	if(Net.networkSignOn()){
	            		//new  SelectServiceFromServer().execute();
	            	}else{
	            		//ALERT
	            	}
	            }
	        	
	        }
	        
	    }
	    
	    @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.main, menu);
			return true;
		}
		
		 @Override
			public void onBackPressed() {
			  
			        new AlertDialog.Builder(this)
			        .setTitle("ออกจากโปรแกรม")
			        .setMessage("ต้องการออกจากโปรแกรม")
			                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface arg0, int arg1) {
			                    	Intent intent = new Intent(BESM_MainForUser.this,BESM_LoginActivity.class);
			                    	
			                		OPERATION=END;
			                		new  UpdateService().execute();
			                		Handler.removeCallbacks(aUpdateCarBalance);
			                    	Handler.removeCallbacks(aUpdateCarBattery);
			                    	Handler.removeCallbacks(aUpdate);
			                    	Handler.removeCallbacks(aUpdateService);
			                    	Handler.removeCallbacks(aCheckMessage);
			                    	if(mAcceptThread != null){
			                			mAcceptThread.cancle();
			                		}
			                		if(mConnectThread != null){
			                			mConnectThread.cancle();
			                		}
			                		startActivity(intent);
			                        finish();
			                    }
			                })
			                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() {

			                    public void onClick(DialogInterface arg0, int arg1) {
			                    	
			                    }
			                }).create().show();
			}

}
